package com.wsz.logistic.controller;

import com.wsz.logistic.common.exception.RTException;
import com.wsz.logistic.common.util.R;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;


@Controller
public class UploadController {
    @RequestMapping("/upload")
    @ResponseBody
    public R upload(MultipartFile file, HttpServletRequest request, String type) {
        if (file.isEmpty()) {
            return R.error("未选择文件！");
        }
        if (!StringUtils.isEmpty(type)) {
            type = type + "/";
        }
        /*获取原文件名称*/
        String originalFileName = file.getOriginalFilename();
        /*获取文件格式*/
        String[] of = originalFileName.split("\\.");
        /*获取UUID作为新文件的文件名*/
        String uuid = DigestUtils.md5Hex(UUID.randomUUID().toString());
        /*拼接最终文件名*/
        String fileName = uuid + "." + of[of.length - 1];
        /*获取日期信息*/
        Date d = new Date();
        int year = d.getYear() + 1900;
        int month = d.getMonth() + 1;
        int date = d.getDate();
        /*获取项目的文件路径*/
        String filePth = request.getRealPath("/static/upload/");
        /*拼接存放文件路径*/
        String savePath = type + year + "/" + (month < 10 ? "0" + month : month) + "/" + (date < 10 ? "0" + date : date) + "/";
        File f = new File(filePth + savePath);
        if (!f.exists()) {
            f.mkdirs();
        }
        File imageFile = new File(filePth + savePath + fileName);
        try {
            /*存入硬盘*/
            file.transferTo(imageFile);
        } catch (IOException e) {
            throw new RTException(e.getMessage());
        }
        if ("edit/".equals(type)) {
            return R.edit(savePath + fileName);
        }
        return R.ok(savePath + fileName);
    }
}
